import random

from django import http
from django.shortcuts import render
from django_redis import get_redis_connection

from libs.captcha.captcha import captcha
# from yuntongxun.sms import CCP

# Create your views here.
from django.views import View

from utils.response_code import RETCODE
# from sms import CCP
from utils.response_code import RET, error_map
from verifications import constants
# from celery_tasks.tasks.sms import send_sms




class ImageCodeView(View):
    def get(self,request,uuid):
        #1.通过captcha模块模块 和 模块内容
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        #2.保存图片内容到redis
        # 保存图片验证码
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, 300, text)

        #3.返回图片给前端
        # 响应图片验证码
        return http.HttpResponse(image, content_type='imgae/jpg')

class SMSCodeView(View):
    """短信验证码"""

    def get(self, reqeust, mobile):
        #初始化数据 mobile,image_code,uuid
        image_code=reqeust.GET.get('image_code').upper()
        image_code_id=reqeust.GET.get('image_code_id')    #
        print(image_code_id)

        #校验数据
        if not all([image_code,image_code_id]):
            return http.HttpResponseForbidden('参数不全')

        redis_conn=get_redis_connection('verify_code')
        redis_image_code=redis_conn.get('img_%s' %image_code_id).decode()      ######
        print(redis_image_code)



        if image_code != redis_image_code:
            return http.HttpResponseForbidden('图片验证码不正确')

        redis_sms_flag=redis_conn.get('sms_flag_%s' %mobile)
        if redis_sms_flag:
            return http.HttpResponseForbidden('不能频繁请求短信')

        # 2.处理业务逻辑
        #补充判断是否在发送中
        # 获取随机短信验证码
        sms_code='%06d' %random.randint(0,999999)
        print(sms_code)

        #保持验证码到redis中
        pl=redis_conn.pipeline()  #提高redis的执行效率
        # redis_conn.setex('sms_%s' %mobile,300,sms_code)   #CACHES配置里面的名字
        # redis_conn.setex('sms_flag_%s' %mobile,60,'sending')
        pl.setex('sms_%s' % mobile, 300, sms_code)  # CACHES配置里面的名字
        pl.setex('sms_flag_%s' % mobile, 60, 'sending')
        pl.execute()

        # ccp=CCP()
        # ccp.send_template_sms(mobile,[sms_code,5],1)

        #异步调用celery的发送短信任务
        send_sms.delay(mobile,sms_code,5,1)



        #返回响应
        res={
            'code':0,
            'errmsg':'success'
        }
        return http.JsonResponse(res)
        pass





